package com.leulounge.util;

import com.couchbase.client.CouchbaseClient;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Stefany Carrillo
 */
public class Connection {

    private static final String host = "http://127.0.0.1:8091/pools";
    private static final String bucket = "llbucket";
    private static final String user = "";
    private static final String pass = "";
    private static final String INTERNAL_ERROR = "1";

    private static CouchbaseClient client;
    private static Connection connection = new Connection();

    private Connection() {
        try {
            client = new CouchbaseClient(
                    Arrays.asList(new URI(host)),
                    bucket, user, pass);
        } catch (URISyntaxException ex) {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
            client = null;
        } catch (IOException ex) {
            Logger.getLogger(Connection.class.getName()).log(Level.SEVERE, null, ex);
            client = null;
        }
    }

    public static Connection getInstance() {
        if (connection == null) {
            synchronized (Connection.class) {
                if (connection == null) {
                    connection = new Connection();
                }
            }
        }
        return connection;
    }

    public Object get(String id) throws Exception {
        if (connection == null) {
            throw new Exception(INTERNAL_ERROR);
        }
        return client.get(id);
    }

    public boolean save(String id, Object object) throws Exception {
        if (connection == null) {
            throw new Exception(INTERNAL_ERROR);
        }
        try {
            return client.set(id, object).get();
        } catch (InterruptedException ex) {
            return false;
        } catch (ExecutionException ex) {
            return false;
        }
    }

}
